using Microsoft.EntityFrameworkCore;
using RBAC.Interstructrue;
using NLog.Web;
using System.Reflection;
using RBAC.Host;
using Yitter.IdGenerator;
using RBAC.Interstructrue.Base;
using RBAC.Host.Service;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using IGeekFan.AspNetCore.Knife4jUI;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(x =>
{
    var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    x.IncludeXmlComments(xmlPath, true);
    x.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "RBAC权限管理API文档",
        Version = "v1",
        Description = "基于角色的权限控制系统，所有接口均带中文注释。"
    });
});
builder.Services.AddDbContext<MYDbContext>(x =>
{
    x.UseMySql(builder.Configuration.GetConnectionString("MySQL"), new MySqlServerVersion("5.7"));
});

// JWT Authentication 配置
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var secretKey = Encoding.UTF8.GetBytes(jwtSettings["SecretKey"]);

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(secretKey),
        ValidateIssuer = true,
        ValidIssuer = jwtSettings["Issuer"],
        ValidateAudience = true,
        ValidAudience = jwtSettings["Audience"],
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero // 默认是5分钟，这里设置为0
    };
});
builder.Services.AddAuthorization();
builder.Host.UseNLog();
builder.Services.AddAutoMapper(typeof(MyAutoMapper));
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
builder.Services.AddScoped(typeof(IService), typeof(Service));
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    //app.UseSwaggerUI();
    app.UseKnife4UI();
}
app.UseCors(x=>x.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
// .....
app.UseAuthentication(); // 认证
app.UseAuthorization(); // 再授权

app.MapControllers();

app.Run();
